<template>
  <view class="follow-page">
    <!-- 分类标签 -->
    <view class="category-tabs">
      <view class="tabs-pill">
        <view 
          class="tab-item" 
          :class="{ active: currentCategory === item.value }"
          v-for="item in categoryList" 
          :key="item.value"
          @click="switchCategory(item.value)"
        >
          {{ item.label }}
        </view>
      </view>
    </view>
    
    <!-- 表头 -->
    <view class="table-header">
      <text class="header-brand">品牌</text>
      <text class="header-price">参考价格</text>
      <text class="header-change">涨跌幅</text>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        class="product-item" 
        v-for="item in productList" 
        :key="item.id"
        @click="goToDetail(item)"
      >
        <view class="product-brand">
          <text class="brand-name">{{ item.name || item.brand }}</text>
          <text class="product-spec">{{ item.spec || item.specification }}</text>
        </view>
        
        <view class="product-price">
          <text class="price-value" :class="(item.price_change || item.change) > 0 ? 'price-up' : ((item.price_change || item.change) < 0 ? 'price-down' : 'price-stable')">{{ item.price || item.current_price }}</text>
        </view>
        
        <view class="product-change">
          <text class="change-value" :class="(item.change_percent || item.price_change || item.change) > 0 ? 'price-up' : ((item.change_percent || item.price_change || item.change) < 0 ? 'price-down' : 'price-stable')">
            {{ formatPriceChange(item.change_percent || item.price_change || item.change) }}
          </text>
      </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && productList.length === 0">
      <u-empty 
        text="暂无关注的商品" 
        icon="heart"
        mode="data"
      ></u-empty>
    </view>
    
    <!-- 加载更多 -->
    <u-loadmore 
      :status="loadmoreStatus" 
      @loadmore="loadMore"
      v-if="productList.length > 0"
    ></u-loadmore>
    
  </view>
</template>

<script>
/**
 * 我的关注页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { favoriteApi } from '@/api'
import { showToast, handleApiError } from '@/utils/common.js'

const { getFollowList } = favoriteApi

export default {
  data() {
    return {
      currentCategory: 'tobacco',
      categoryList: [
        { label: '口粮', value: 'tobacco' },
        { label: '酒', value: 'alcohol' },
        { label: '茶', value: 'tea' }
      ],
      productList: [],
      loading: false,
      loadmoreStatus: 'loadmore',
      currentPage: 1,
      pageSize: 20,
      hasMore: true
    }
  },
  
  onLoad() {
    this.loadFavoriteList()
  },
  
  onShow() {
    this.refreshList()
  },
  
  onPullDownRefresh() {
    this.refreshList()
  },
  
  onReachBottom() {
    this.loadMore()
  },
  
  methods: {

    
    // 切换分类
    switchCategory(category) {
      this.currentCategory = category
      this.refreshList()
    },
    
    // 刷新列表
    refreshList() {
      this.currentPage = 1
      this.hasMore = true
      this.productList = []
      this.loadFavoriteList()
    },
    
    // 加载收藏列表
    async loadFavoriteList() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      this.loadmoreStatus = 'loading'
      
      try {
        // 检查登录状态
        const userToken = uni.getStorageSync('user_token')
        if (!userToken) {
          this.loading = false
          this.loadmoreStatus = 'loadmore'
          showToast('请先登录查看收藏列表')
          return
        }
        
        const params = {
          user_token: userToken,
          page: this.currentPage,
          limit: this.pageSize,
          category: this.currentCategory
        }
        
        const response = await getFollowList(params)

        const listPayload = (response && response.code === 0) ? (response.data || response) : response
        const dataList = Array.isArray(listPayload) ? listPayload : (listPayload?.data || [])
        if (Array.isArray(dataList)) {
          const newList = dataList.map(item => ({
            id: item.product_id || item.id,
            product_id: item.product_id || item.id,
            name: item.product_name || item.name,
            brand: item.brand,
            spec: item.spec || item.specification,
            specification: item.specification || item.spec,
            price: parseFloat(item.current_price || item.market_price || 0).toFixed(1),
            current_price: parseFloat(item.current_price || item.market_price || 0).toFixed(1),
            change: parseFloat(item.price_change || item.change_amount || 0),
            price_change: parseFloat(item.price_change || item.change_amount || 0),
            change_percent: parseFloat(item.change_percent || item.change_rate || 0),
            category: item.category,
            update_time: item.update_time,
            cover: item.cover || item.image_url || '',
            is_followed: true
          }))
          
          if (this.currentPage === 1) {
            this.productList = newList
          } else {
            this.productList.push(...newList)
          }
          
          this.hasMore = (typeof listPayload?.has_more !== 'undefined') ? !!listPayload.has_more : (newList.length >= this.pageSize)
          if (this.hasMore) {
            this.currentPage++
          }
          this.loadmoreStatus = this.hasMore ? 'loadmore' : 'nomore'
        } else {
          handleApiError(response)
          this.loadmoreStatus = 'loadmore'
        }
      } catch (error) {
        console.error('加载关注列表失败:', error)
        
        showToast('网络错误', 'none')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return
      this.loadFavoriteList()
    },

    // 获取价格变化样式类
    getPriceChangeClass(change) {
      if (change > 0) return 'price-up'
      if (change < 0) return 'price-down'
      return 'price-stable'
    },

    // 格式化价格变化
    formatPriceChange(change) {
      if (change === 0) return '0.0'
      const value = Math.abs(change).toFixed(1)
      return `${value}`
    },

    // 跳转到商品详情
    goToDetail(item) {
      const id = item.id || item.product_id
      const name = encodeURIComponent(item.name || item.brand || '')
      const spec = encodeURIComponent(item.spec || item.specification || '')
      
      uni.navigateTo({
        url: `/pages/product/detail?id=${id}&name=${name}&spec=${spec}`
      })
    },
    

  }
}
</script>

<style scoped>
.follow-page {
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  justify-content: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.tabs-pill {
  display: flex;
  background: #fff;
  border: 2rpx solid #ea4148;
  border-radius: 60rpx;
  overflow: hidden;
}

.tab-item {
  padding: 10rpx 80rpx;
  font-size: 28rpx;
  color: #ea4148;
  background: #fff;
  border-right: 1px solid #ea4148;
}

.tab-item:last-child {
  border-right: none;
}

.tab-item.active {
  color: #fff;
  background: #ea4148;
}

/* 表头 */
.table-header {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #e8e8e8;
}

.header-brand {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.header-price {
  width: 160rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.header-change {
  width: 120rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

/* 商品列表 */
.product-list {
  background-color: #fff;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
}

.product-item:last-child {
  border-bottom: none;
}

.product-brand {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.brand-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.product-spec {
  font-size: 24rpx;
  color: #999;
}

.product-price {
  width: 160rpx;
  text-align: center;
}

.price-value {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.product-change {
  width: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.change-value {
  font-size: 28rpx;
  font-weight: 500;
  margin-right: 4rpx;
}

.change-value.price-up {
    color: #ea4148;
}

.change-value.price-down {
    color: #29af5a;
}

.change-value.price-stable {
  color: #999;
}

.price-value.price-up { color: #ea4148; }
.price-value.price-down { color: #29af5a; }
.price-value.price-stable { color: #999; }

.change-value::after { font-family: 'uicon-iconfont'; margin-left: 4rpx; }
.change-value.price-up::after { content: '↑'; }
.change-value.price-down::after { content: '↓'; }
.change-value.price-stable::after { content: '-'; }


/* 空状态 */
.empty-state {
  padding: 100rpx 0;
  background-color: #fff;
}
</style>
